using System;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvivor
{


	[Serializable]
	public class EnemyWave
	{
		public float GenerateDuration = 1;
		public GameObject EnemyPrefab;
		public int Seconds = 10;
	}
	
	public partial class EnemyGenerator : ViewController
	{
		private float mCurrentGenerateSeconds = 0;
		private float mCurrentWaveSeconds = 0;

		public static BindableProperty<int> EnemyCount = new BindableProperty<int>(0);
		
		[SerializeField]
		public List<EnemyWave> EnemyWaves = new List<EnemyWave>();

		private Queue<EnemyWave> mEnemyWavesQueue = new Queue<EnemyWave>();

		public int WaveCount = 0;
		
		//public int RemainWaveCount => mEnemyWavesQueue.Count;
		public bool LastWave => WaveCount == EnemyWaves.Count;

		public EnemyWave CurrentWave => mCurrentWave;
		private void Start()
		{
			foreach (var enemyWave in EnemyWaves)
			{
				mEnemyWavesQueue.Enqueue(enemyWave);
			}
		}

		private EnemyWave mCurrentWave = null;

		private void Update()
		{
			if (mCurrentWave == null)
			{
				if (mEnemyWavesQueue.Count > 0)
				{
					WaveCount++;
					mCurrentWave = mEnemyWavesQueue.Dequeue();
					mCurrentGenerateSeconds = 0;
					mCurrentWaveSeconds = 0;
				}
			}

			if (mCurrentWave != null)
			{
				mCurrentGenerateSeconds += Time.deltaTime;
				mCurrentWaveSeconds += Time.deltaTime;



				if (mCurrentGenerateSeconds >= mCurrentWave.GenerateDuration)
				{
					mCurrentGenerateSeconds = 0;
					var player = Player.Default;
					if (player)
					{
						var randomAngle = Random.Range(0, 360f);
						var randomRadius = randomAngle * Mathf.Deg2Rad;
						var direction = new Vector3(Mathf.Cos(randomRadius), Mathf.Sin(randomRadius));
						var generatePos = player.transform.position + direction * 10;
						Enemy.Instantiate()
							.Position(generatePos)
							.Show();
					}
					
					if (mCurrentWaveSeconds >= mCurrentWave.Seconds)
					{
						//mCurrentWaveSeconds = 0;
						mCurrentWave = null;
					}
				}
			}
		}
	}
}
